﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.System;
using Windows.System.Display;
using Windows.System.Profile;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using ArticleandSiteData;
using SplitViewOptions.BusinessControl;
using SplitViewOptions.Model;
using webRuntimeComponent;
using Buffer = Windows.Storage.Streams.Buffer;
using Windows.ApplicationModel;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234238 上提供

namespace SplitViewOptions
{
    /// <summary>
    ///     可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class HomePage : Page
    {
        //页面代码太多，建议分开
        public HomePage()
        {
            InitializeComponent();
            //var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
            //coreTitleBar.ExtendViewIntoTitleBar = true;
            App.Issecondwebviewmanipulated = false;
            MyEvent.BtnEvent += showmenubtn_Click;
            //  Clipboard.ContentChanged += Clipboard_ContentChanged;
            Application.Current.Suspending += new SuspendingEventHandler(App_Suspending);
            Application.Current.Resuming += new EventHandler<Object>(App_Resuming);

            _popup.Child = btn;
            App.key = 0;
            btn.Click += Btn_Click;
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            {
                //ChangeUserAgent(add);
            }
            //   secondpopup.Child = secondwebview;
            if (App.Isbackgroundmode)
            {
                //webviewgrid.Children.Remove(homewebview);
                homewebview = new WebView(WebViewExecutionMode.SeparateThread);
            }
            else
            {
                homewebview = new WebView(WebViewExecutionMode.SameThread);
            }
            webviewgrid.Children.Insert(0, homewebview);
            //Canvas.SetZIndex(homewebview, 10);


            var wbsetting = homewebview.Settings;
            // homewebview.AllowedScriptNotifyUris.Add(App.currenturl);        
            wbsetting.IsJavaScriptEnabled = true;
            wbsetting.IsIndexedDBEnabled = true;

            DataTransferManager.GetForCurrentView().DataRequested += dataTransferManager_DataRequested;
            homewebview.ContainsFullScreenElementChanged += Homewebview_ContainsFullScreenElementChanged;
            homewebview.ContentLoading += Homewebview_ContentLoading;
            homewebview.DOMContentLoaded += Homewebview_DOMContentLoaded;
            homewebview.FrameContentLoading += Homewebview_FrameContentLoading;
            homewebview.FrameDOMContentLoaded += Homewebview_FrameDOMContentLoaded;
            homewebview.FrameNavigationCompleted += Homewebview_FrameNavigationCompleted;
            homewebview.FrameNavigationStarting += Homewebview_FrameNavigationStarting;
            homewebview.KeyDown += Homewebview_KeyDown;
            homewebview.LoadCompleted += Homewebview_LoadCompleted;
            homewebview.Loaded += Homewebview_Loaded;
            homewebview.Loading += Homewebview_Loading;
            homewebview.LongRunningScriptDetected += Homewebview_LongRunningScriptDetected;
            homewebview.NavigationCompleted += Homewebview_NavigationCompleted;
            homewebview.NavigationFailed += Homewebview_NavigationFailed;
            homewebview.NavigationStarting += Homewebview_NavigationStarting;
            homewebview.PermissionRequested += Homewebview_PermissionRequested;
            homewebview.UnsafeContentWarningDisplaying += Homewebview_UnsafeContentWarningDisplaying;
            homewebview.UnsupportedUriSchemeIdentified += Homewebview_UnsupportedUriSchemeIdentified;
            homewebview.PointerEntered += Homewebview_PointerEntered;
            homewebview.UnviewableContentIdentified += Homewebview_UnviewableContentIdentified;
            homewebview.ScriptNotify += homewebview_ScriptNotify;
            homewebview.NewWindowRequested += homewebview_NewWindowRequested;
            Add_Click();
            App.Picnel = picstackpanel;
            App.Menutoatlpicnel = menurelativepanel;
            if (App.Isnightmode)
            {
                Background = new SolidColorBrush(Colors.Black);
                // this.Opacity = 0.2;
            }
            else
            {
                Background = new SolidColorBrush(Colors.Transparent);
                Opacity = 1;
            }
            if (App.Isfully)
            {
                if (App.Mainmenugrid != null)
                {
                    App.Mainmenugrid.Visibility = Visibility.Collapsed;
                }
                menurelativepanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (App.Mainmenugrid != null)
                {
                    App.Mainmenugrid.Visibility = Visibility.Visible;
                }
                menurelativepanel.Visibility = Visibility.Collapsed;
            }
            if (App.Isunlocksmode)
            {
                if (_dispRequest == null)
                {
                    // Activate a display-required request. If successful, the screen is 
                    // guaranteed not to turn off automatically due to user inactivity.
                    _dispRequest = new DisplayRequest();
                    _dispRequest.RequestActive();
                }
            }
        }
        private static readonly ApplicationDataContainer _localSettings =
         ApplicationData.Current.LocalSettings;
        private void App_Resuming(object sender, object e)
        {
            if(_localSettings.Values.Keys.Contains("leaveurl"))
            {
                string url = _localSettings.Values["leaveurl"].ToString();
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                homewebview.Navigate(App.Currenturl);
            }
        }

        private void App_Suspending(object sender, SuspendingEventArgs e)
        {
            _localSettings.Values["leaveurl"] = homewebview.Source.AbsoluteUri;
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e) 
        {
            App.isgoingback = false;
            Debug.WriteLine(App.Currenturl.Host + "host");
            //   App.titlebox.Text = App.currenturl.AbsoluteUri;
            // App.currenturl = new Uri("http://live3.win007.com/");
            App.Webview = homewebview;
            //Uri MyUrl = homewebview.BuildLocalStreamUri("MyContent", "/my.html");
            if (App.Isdownloadstirngmode)
            {
                Debug.WriteLine("isdownloadstirngmode=FTRUE OnNavigatedTo");
                var oldsrcreplacestr = "src=\"/";
                var newsrcreplacestr = "src=\"http://" + App.Currenturl.Host + "/";
                var oldhrefreplacestr = "href=\"/";
                var oldhrefwithemptyreplacestr = "href=\"/ ";
                var newhrefreplacestr = "href=\"http://" + App.Currenturl.Host + "/";
                App.Htmlstringcontent = await HtmlUsedFunction.gethtmlstring(App.Currenturl.AbsoluteUri);
                var ScriptTagString = "<script type=\"text/javascript\">";
                var strr =
                    "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  window.external.notify(this.src);  }; } }";
                var IndexOfScriptTag = App.Htmlstringcontent.IndexOf("</head>");
                var InsertionScriptString = strr;
                var endscript = "</script>";
                App.Htmlstringcontent = App.Htmlstringcontent.Insert(IndexOfScriptTag,
                    ScriptTagString + InsertionScriptString + endscript);
                Debug.WriteLine(ScriptTagString + InsertionScriptString + endscript);
                App.Htmlstringcontent =
                    App.Htmlstringcontent.Replace(oldsrcreplacestr, newsrcreplacestr)
                        .Replace(oldhrefreplacestr, newhrefreplacestr)
                        .Replace(oldhrefwithemptyreplacestr, newhrefreplacestr);
                Debug.WriteLine("new httpstring");
                Debug.WriteLine(App.Htmlstringcontent);
                if (App.Htmlstringcontent.Length > 500)
                {
                    if (App.Iswithoutpicmode)
                    {
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("jpg", "1jpg");
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("png", "1png");

                        // reuslt = reuslt.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
                        // MyWebview.NavigateToString(reuslt);
                        Debug.WriteLine(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                    else
                    {
                        Debug.WriteLine(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                }
                else
                {
                    if (App.Ismobile)
                    {
                        App.Navigatemobilemode(homewebview, App.Currenturl);
                    }
                    else
                    {
                        homewebview.Navigate(App.Currenturl);
                    }
                }
            }
            else
            {
                Debug.WriteLine("isdownloadstirngmode=FALSE OnNavigatedTo");

                if (App.Ismobile)
                {
                    App.Navigatemobilemode(homewebview, App.Currenturl);
                }
                else
                {
                    homewebview.Navigate(App.Currenturl);
                }
            }
            //   menurelativepanel.Visibility = Visibility.Visible;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            homewebview.Stop();
            App.Webview = null;
            if (_doublebtn != null)
            {
                _doublebtn.Content = "添加双屏";
            }
            App.Titlebox.Text = string.Empty;
            //   timer.Stop();
            MyEvent.BtnEvent -= showmenubtn_Click;
            if (_dispRequest != null)
            {
                // Deactivate the display request and set the var to null.
                _dispRequest.RequestRelease();
                _dispRequest = null;
            }
            base.OnNavigatedFrom(e);
        }

        //[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
        //private static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);

        //const int URLMON_OPTION_USERAGENT = 0x10000001;
        //public void ChangeUserAgent(string Agent)
        //{
        //    UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, Agent, Agent.Length, 0);
        //}
        private string _addUsage =
            "Mozilla/5.0 (Linux; U; Android 2.2; en-gb; GT-P1000 Build/FROYO) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1";
        //从来没用
        private bool _isfirstna = true;
        private readonly Random _ran = new Random();

        //不建议写在这
        private readonly Button btn = new Button
        {
            Content = "用百度搜索",
            Foreground = new SolidColorBrush(Colors.Blue)
        };

        // Create this variable at a global scope. Set it to null.
        private DisplayRequest _dispRequest;
        //Popup secondpopup = new Popup();
        //WebView secondwebview = new WebView();
        private Button _doublebtn;
        //DisplayRequest
        // Global Transform used to change the position of the Rectangle.
        private TranslateTransform _dragTranslation;
        private readonly WebView homewebview;
        private int i;
        private Popup _popup = new Popup();
        private string _pageselectedtext = string.Empty;
        private DispatcherTimer _timer = new DispatcherTimer();

        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            _pageselectedtext = string.Empty;
            _popup.IsOpen = false;
            var url = "https://www.baidu.com/s?wd=" + _pageselectedtext;
            App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
            homewebview.Navigate(App.Currenturl);
        }

        private void WinRTObject_NumberChanged(object sender, TextChangeEventArgs e)
        {
            var URL = e.Message;
            Debug.WriteLine(URL);
            ParseUrl(URL);
        }

        private void WinRTObject_DoWork(string str)
        {
            var URL = str;
            Debug.WriteLine(URL);
            ParseUrl(URL);
        }

        private void ParseUrl(string url)
        {
            var Text = url;
            var tem = new SolidColorBrush
            (Color.FromArgb(255, Convert.ToByte(_ran.Next(0, 255)),
                Convert.ToByte(_ran.Next(0, 255)),
                Convert.ToByte(_ran.Next(0, 255))));
            if (Text.Contains(".jpeg") || Text.Contains(".gif") || Text.Contains(".jpg") || Text.Contains(".png") ||
                Text.Contains(".1jpg") || Text.EndsWith(".1png"))
            {
                _popup.IsOpen = false;
                picstackpanel.Visibility = Visibility.Visible;
                picsavebtn.Tag = Text;
                sharepic.Tag = Text;

                picsavebtn.Foreground = tem;
                sharepic.Foreground = tem;
                picsavetolibrarybtn.Foreground = tem;
                picsavetolibrarybtn.Tag = Text;
                return;
            }
            if (Text.StartsWith("http"))
            {
                _popup.IsOpen = false;
                if (Text.Contains(".mp4") || Text.Contains(".3gp"))
                {
                    picstackpanel.Visibility = Visibility.Visible;
                    menurelativepanel.Visibility = Visibility.Visible;
                    savevideo.Tag = Text;
                    savevideo.Foreground = tem;
                }
                else
                {
                    picstackpanel.Visibility = Visibility.Visible;
                    picsavebtn.Tag = Text;
                    sharepic.Tag = Text;
                    menurelativepanel.Visibility = Visibility.Visible;
                    picsavebtn.Foreground = tem;
                    sharepic.Foreground = tem;
                    picsavetolibrarybtn.Foreground = tem;
                    picsavetolibrarybtn.Tag = Text;
                }
                return;
            }
            if (Text.StartsWith("1") || Text.StartsWith("2") || Text.StartsWith("3") || Text.StartsWith("4") ||
                Text.StartsWith("5") || Text.StartsWith("6") || Text.StartsWith("7") || Text.StartsWith("8") ||
                Text.StartsWith("9"))
            {
                //string[] o = Text.Split(',');


                //if (!string.IsNullOrEmpty(pageselectedtext))
                //{
                //    p.IsOpen = true;
                //    p.HorizontalOffset = int.Parse(o[0]);
                //    p.VerticalOffset = int.Parse(o[1]);
                //}
                //else
                //{
                //    p.IsOpen = false;
                //}
                return;
            }
            _pageselectedtext = Text;
        }

        private void Homewebview_PointerEntered(object sender, PointerRoutedEventArgs e)
        {
            Debug.WriteLine("Homewebview_PointerEntered");
        }

        private void Homewebview_UnviewableContentIdentified(WebView sender,
            WebViewUnviewableContentIdentifiedEventArgs args)
        {
            Debug.WriteLine("Homewebview_UnviewableContentIdentified");
        }

        private void Homewebview_UnsupportedUriSchemeIdentified(WebView sender,
            WebViewUnsupportedUriSchemeIdentifiedEventArgs args)
        {
            if (args.Uri.AbsoluteUri.Contains("ms-windows-store:"))
            {
                args.Handled = false;
            }
            else
            {
                args.Handled = true;
            }
            Debug.WriteLine("Homewebview_UnsupportedUriSchemeIdentified");
            // args.Handled = true;
        }

        private void Homewebview_UnsafeContentWarningDisplaying(WebView sender, object args)
        {
            Debug.WriteLine("Homewebview_UnsafeContentWarningDisplaying");
        }

        private void Homewebview_PermissionRequested(WebView sender, WebViewPermissionRequestedEventArgs args)
        {
            Debug.WriteLine("Homewebview_PermissionRequested");
            //if( args.PermissionRequest.PermissionType== WebViewPermissionType.Geolocation)
            //  {
            //      args.PermissionRequest.Allow();
            //  }
            //  if (args.PermissionRequest.PermissionType == WebViewPermissionType.Media)
            //  {
            //      args.PermissionRequest.Allow();
            //  }
            //  if (args.PermissionRequest.PermissionType == WebViewPermissionType.UnlimitedIndexedDBQuota)
            //  {
            //      args.PermissionRequest.Allow();
            //  }
            args.PermissionRequest.Allow();
        }

        private async void Homewebview_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            //if(App.isgoingback)
            //{
            //    args.Cancel = true;
            //    return;
            //}
            Debug.WriteLine(args.Uri.AbsoluteUri);
            Debug.WriteLine(args.Uri.AbsoluteUri);
            Debug.WriteLine(args.Uri.Host);
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            {
                // ChangeUserAgent(add);
                if (App.Ismobile)
                {
                    if (App.Ischangeuseragnet)
                    {
                        args.Cancel = true;
                        App.Ischangeuseragnet = false;
                        App.Navigatemobilemode(homewebview, args.Uri);
                    }
                    //if (App.ischangeuseragnet)
                    //{
                    //    //return;
                    //    //args.Cancel = true;
                    //    //isfirstna = false;
                    //    //App.navigatemobilemode(homewebview, args.Uri);
                    //}
                    //else
                    //{
                    //    args.Cancel = true;
                    //    //isfirstna = false;
                    //    App.navigatemobilemode(homewebview, args.Uri);
                    //    // args.Cancel = true;
                    //}
                }
            }


            // bool  containsdomin =HtmlUsedFunction.containsdomainname(args.Uri.Host);
            if (App.Isdownloadstirngmode)
            {
                //App.isdownloadstirngmode = true;
                Debug.WriteLine("App.isdownloadstirngmode==true");
                if (args.Uri != null)
                {
                    Debug.WriteLine("arg" + args.Uri.AbsoluteUri);
                    if (args.Uri.AbsoluteUri.StartsWith("http"))
                    {
                        await HtmlUsedFunction.changehtmlurl(args.Uri.AbsoluteUri, homewebview);
                    }
                    else
                    {
                        var elsestrna = "http://" + App.Currenturl.Host + "/" + args.Uri.AbsoluteUri;
                        Debug.WriteLine("arg" + elsestrna);
                        await HtmlUsedFunction.changehtmlurl(elsestrna, homewebview);
                    }
                }
            }
            //App.htmlstringcontent = string.Empty;
            Debug.WriteLine("Homewebview_NavigationStarting");
            //localprogressinfo.Update(0.1, "NavigationStarting");
            //localprogressinfo.Opacity = 1;
            App.Currenturl = args.Uri;
        }

        private void Homewebview_NavigationFailed(object sender, WebViewNavigationFailedEventArgs e)
        {
            Debug.WriteLine("Homewebview_NavigationFailed");
            localprogressinfo.Update(0.1, "NavigationFailed");
            localprogressinfo.Opacity = 1;
        }

        private void Homewebview_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            Debug.WriteLine("Homewebview_NavigationCompleted");
            localprogressinfo.Update(0.8, "NavigationCompleted");
            localprogressinfo.Opacity = 0;
            App.Ischangeuseragnet = true;
        }

        private void Homewebview_LongRunningScriptDetected(WebView sender,
            WebViewLongRunningScriptDetectedEventArgs args)
        {
            Debug.WriteLine("Homewebview_LongRunningScriptDetected");
            localprogressinfo.Update(0.3, "LongRunningScriptDetected");
            localprogressinfo.Opacity = 1;
        }

        private void Homewebview_Loading(FrameworkElement sender, object args)
        {
            localprogressinfo.Update(0.2, "Loading");
            localprogressinfo.Opacity = 1;
            Debug.WriteLine("Homewebview_Loading");
        }

        private void Homewebview_Loaded(object sender, RoutedEventArgs e)
        {
            Debug.WriteLine("Homewebview_Loaded");
            localprogressinfo.Update(0.3, "Loaded");
            localprogressinfo.Opacity = 1;
        }

        private async void Homewebview_LoadCompleted(object sender, NavigationEventArgs e)
        {
            HistoryWebModel.HistoryWeb.Add(new History
            {
                Title = homewebview.DocumentTitle,
                Url = App.Currenturl
            });
            try
            {
                #region

                if (App.Isdownloadstirngmode)
                {
                    Debug.WriteLine("App.isdownloadstirngmode=TRUE,,LOADCOMPLETED");
                    var pramslist = new List<string>();
                    pramslist.Add("dfafdsa");
                    var utyustr = await homewebview.InvokeScriptAsync("SayHelloWorld", pramslist);
                    if ((e.Uri != null) && e.Uri.AbsoluteUri.ToLower().StartsWith("http"))
                    {
                    }
                    else
                    {
                        if ((e.Uri != null) && e.Uri.AbsoluteUri.ToLower().StartsWith("about"))
                        {
                            if (e.Uri.AbsoluteUri.Contains("About"))
                            {
                                var url = e.Uri.AbsoluteUri.Replace("About", "http");
                                Debug.WriteLine("App.isdownloadstirngmode=TRUE,,LOADCOMPLETED  changehtmlurl");

                                await HtmlUsedFunction.changehtmlurl(url, homewebview);
                            }
                            if (e.Uri.AbsoluteUri.Contains("about"))
                            {
                                var url = e.Uri.AbsoluteUri.Replace("about", "http");
                                await HtmlUsedFunction.changehtmlurl(url, homewebview);
                            }
                        }
                    }
                }
                else
                {
                    Debug.WriteLine("App.isdownloadstirngmode=FALSE,,LOADCOMPLETED  ");
                }
                localprogressinfo.Update(1, "LoadCompleted");
                localprogressinfo.Opacity = 0;
                Debug.WriteLine("Homewebview_LoadCompleted");
                if ((App.Titlebox != null) && (e.Uri != null) && (e.Uri.AbsoluteUri != null))
                {
                    App.Titlebox.Text = e.Uri.AbsoluteUri;
                }

                #endregion
            }
            catch (Exception ex)
            {
            }
            finally
            {
                var time = DateTime.Now;
                HistoryWebModel.HistoryWeb.Add(new History
                {
                    Title = homewebview.DocumentTitle,
                    Url = homewebview.Source
                });
                var videotaghref1 =
                    "   var videotag1 = document.getElementsByTagName(\"video\");   for (var i = 0; i < videotag1.length; i++) {    videotag1[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";
                var videoeval1 = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        videotaghref1
                    });
                //  var _WidthString = await homewebview.InvokeScriptAsync("eval",
                //new[] { "var k=document.body.scrollWidth.toString(); NotifyApp.setKeyCombination(k)" });
                //string getwidthstr = "var wid=document.body.clientWidth;alert(wid);";
                //var getwidthstreval1 = await homewebview.InvokeScriptAsync("eval",
                //new[] { getwidthstr });
            }
            //var _WidthString =await homewebview.InvokeScriptAsync("eval",
            //    new[] { "document.body.scrollWidth.toString()" });
            //int _ContentWidth;
            //if (!int.TryParse(_WidthString, out _ContentWidth))
            //    throw new Exception(string.Format("failure/width:{0}", _WidthString));


            //// ask the content its height
            //var _HeightString =await homewebview.InvokeScriptAsync("eval",
            //    new[] { "document.body.scrollHeight.toString()" });
            //int _ContentHeight;
            //if (!int.TryParse(_HeightString, out _ContentHeight))
            //    throw new Exception(string.Format("failure/height:{0}", _HeightString));
        }

        private void Homewebview_LayoutUpdated(object sender, object e)
        {
            Debug.WriteLine("Homewebview_LayoutUpdated");
        }

        private void Homewebview_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            Debug.WriteLine("Homewebview_KeyDown");
        }

        private void Homewebview_FrameNavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameNavigationStarting");
            localprogressinfo.Update(0.4, "FrameNavigationStarting");
            localprogressinfo.Opacity = 1;
        }

        private void Homewebview_FrameNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameNavigationCompleted");
            localprogressinfo.Update(0.9, "FrameNavigationCompleted");
            localprogressinfo.Opacity = 0;
        }

        private async void Homewebview_FrameDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameDOMContentLoaded");
            localprogressinfo.Update(0.7, "FrameDOMContentLoaded");
            try
            {
                // WebView native object must be inserted in the OnNavigationStarting event handler
                var winRTObject = new KeyHandler();
                // Expose the native WinRT object on the page's global object
                homewebview.AddWebAllowedObject("NotifyApp", winRTObject);
                //   winRTObject.DoWork += WinRTObject_DoWork;
                winRTObject.NumberChanged += WinRTObject_NumberChanged;
                // inject event handler to arbitrary page once the DOM is loaded
                //  "document.getElementById(\"hnmain\").addEventListener(\"click\", function () { NotifyApp.setKeyCombination(43); }); " 
                //string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } }";

                //string tevalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";

                //var ateval = await homewebview.InvokeScriptAsync("eval", new[] { tevalstr });
                var evalstr =
                    "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onclick = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";
                var evalmibimgstr =
                    "   var mibimgboxes = document.getElementsByTagName(\"mib-img\");   for (var i = 0; i < mibimgboxes.length; i++) {    mibimgboxes[i].onclick = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";
                var imgeval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        evalstr
                    });
                var mibimgeval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        evalmibimgstr
                    });
                //  string ataghref = "   var atag = document.getElementsByTagName(\"a\");   for (var i = 0; i < atag.length; i++) {    atag[i].onclick = function(){  NotifyApp.setKeyCombination(this.href);  }; } ";
                //  var aeval = await homewebview.InvokeScriptAsync("eval",
                //new[] { ataghref });
                var videotaghref =
                    "   var videotag = document.getElementsByTagName(\"video\");   for (var i = 0; i < videotag.length; i++) {    videotag[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";
                var videoeval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        videotaghref
                    });
                var getselectedtext =
                    "document.onmouseup=function(){ var txt = window.getSelection();  var stin=txt.toString();  NotifyApp.setKeyCombination(stin);    }";
                var vgetselectedtexteval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        getselectedtext
                    });
                // string getmousepostion = "document.onmousedown=function(event){    var e = event || window.event;  var postr=e.clientX.toString()+\",\"+e.clientY.toString();NotifyApp.setKeyCombination(postr);    }";
                // var getmousepostioneval = await homewebview.InvokeScriptAsync("eval",
                //new[] { getmousepostion });
                //string aevalstr = "   var aboxes = document.getElementsByTagName(\"a\");   for (var i = 0; i < aboxes.length; i++) {    aboxes[i].onclick = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";

                //var aimgeval = await homewebview.InvokeScriptAsync("eval",
                //new[] { aevalstr });
                //  App.isnightmode = true;
                if (App.Isnightmode)
                {
                    var bodyback = await homewebview.InvokeScriptAsync("eval",
                        new[]
                        {
                            App.nd
                        });
                    Debug.WriteLine(bodyback);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            localprogressinfo.Opacity = 0.5;
        }

        private void Homewebview_FrameContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameContentLoading");
            localprogressinfo.Update(0.6, "FrameDOMContentLoaded");
            localprogressinfo.Opacity = 1;
        }

        private async void Homewebview_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            Debug.WriteLine("Homewebview_DOMContentLoaded");
            localprogressinfo.Update(0.7, "FrameDOMContentLoaded");
            localprogressinfo.Opacity = 1;
            if (AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop")
            {
                // ChangeUserAgent(add);
                if (App.Ismobile)
                {
                    //  App.ischangeuseragnet = false;
                }
            }
            try
            {
                // WebView native object must be inserted in the OnNavigationStarting event handler
                var winRTObject = new KeyHandler();
                // Expose the native WinRT object on the page's global object
                homewebview.AddWebAllowedObject("NotifyApp", winRTObject);
                //   winRTObject.DoWork += WinRTObject_DoWork;
                winRTObject.NumberChanged += WinRTObject_NumberChanged;
                // inject event handler to arbitrary page once the DOM is loaded
                //  "document.getElementById(\"hnmain\").addEventListener(\"click\", function () { NotifyApp.setKeyCombination(43); }); " 
                //string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } }";

                //string tevalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";

                //var ateval = await homewebview.InvokeScriptAsync("eval", new[] { tevalstr });
                var evalstr =
                    "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onmousedown = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";

                var imgeval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        evalstr
                    });
                //  string ataghref = "   var atag = document.getElementsByTagName(\"a\");   for (var i = 0; i < atag.length; i++) {    atag[i].onclick = function(){  NotifyApp.setKeyCombination(this.href);  }; } ";
                //  var aeval = await homewebview.InvokeScriptAsync("eval",
                //new[] { ataghref });
                var videotaghref =
                    "   var videotag = document.getElementsByTagName(\"video\");   for (var i = 0; i < videotag.length; i++) {    videotag[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";
                var videoeval = await homewebview.InvokeScriptAsync("eval",
                    new[]
                    {
                        videotaghref
                    });
                // App.isnightmode = true;
                if (App.Isnightmode)
                {
                    var bodyback = await homewebview.InvokeScriptAsync("eval",
                        new[]
                        {
                            App.nd
                        });
                    Debug.WriteLine(bodyback);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }

        private void Homewebview_ContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
        {
            Debug.WriteLine("Homewebview_ContentLoading");
            localprogressinfo.Update(0.5, "FrameDOMContentLoaded");
            localprogressinfo.Opacity = 1;
        }

        private void Homewebview_ContainsFullScreenElementChanged(WebView sender, object args)
        {
            Debug.WriteLine("Homewebview_ContainsFullScreenElementChanged");
        }

        private async void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            var request = args.Request;
            //We are going to use an async API to talk to the webview, so get a deferral for the results
            var deferral = args.Request.GetDeferral();
            var dp = await homewebview.CaptureSelectedContentToDataPackageAsync();
            if ((dp != null) && (dp.GetView().AvailableFormats.Count > 0))
            {
                // Webview has a selection, so we'll share its data package
                dp.Properties.Title = "来自多彩浏览器的分享";
                request.Data = dp;
            }
            else
            {
                // No selection, so we'll share the url of the webview
                var myData = new DataPackage();
                myData.SetWebLink(homewebview.Source);
                myData.Properties.Title = "来自多彩浏览器的分享";
                myData.Properties.Description = homewebview.Source.ToString();
                request.Data = myData;
            }
            deferral.Complete();
        }

        private async void getscreen_Click(object sender, RoutedEventArgs e)
        {
            //InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
            //await homewebview.CapturePreviewToStreamAsync(ms);
            //IBuffer ibuffer =await toBuffer(ms);
            //SaveImage(ibuffer);
            //Create a small thumbnail
            //int longlength = 180, width = 0, height = 0;
            //double srcwidth = homewebview.ActualWidth, srcheight = homewebview.ActualHeight;
            //double factor = srcwidth / srcheight; if (factor < 1)
            //{ height = longlength; width = (int)(longlength * factor); }
            //else { width = longlength; height = (int)(longlength / factor); }
            //BitmapSource small = await resize(width, height, ms);   
            var stream = new InMemoryRandomAccessStream();

            await homewebview.CapturePreviewToStreamAsync(stream);

            // Scale the bitmap to the space available for the thumbnail image,
            // preserving aspect ratio.
            double thumbnailWidth = 480;
            double thumbnailHeight = 800;
            var webViewControlWidth = homewebview.ActualWidth;
            var webViewControlHeight = homewebview.ActualHeight;
            if ((thumbnailWidth == 0) || (thumbnailHeight == 0) ||
                (webViewControlWidth == 0) || (webViewControlHeight == 0))
            {
                // Avoid 0x0 bitmaps, which cause all sorts of problems.
                return;
            }

            var horizontalScale = thumbnailWidth/webViewControlWidth;
            var verticalScale = thumbnailHeight/webViewControlHeight;
            var scale = Math.Min(horizontalScale, verticalScale);
            var width = (int) (webViewControlWidth*scale);
            var height = (int) (webViewControlHeight*scale);
            var thumbnailBitmap = await CreateScaledBitmapFromStreamAsync(width, height, stream);
            var pne = new Random();
            var jk = pne.Next(1, 100000000);
            await HtmlUsedFunction.SaveToPngImage(thumbnailBitmap, PickerLocationId.PicturesLibrary, "多彩浏览器器" + jk);
        }

        private static async Task<WriteableBitmap> CreateScaledBitmapFromStreamAsync(int width, int height,
            IRandomAccessStream source)
        {
            var bitmap = new WriteableBitmap(width, height);
            var decoder = await BitmapDecoder.CreateAsync(source);
            var transform = new BitmapTransform();
            transform.ScaledHeight = (uint) height;
            transform.ScaledWidth = (uint) width;
            var pixelData = await decoder.GetPixelDataAsync(
                BitmapPixelFormat.Bgra8,
                BitmapAlphaMode.Straight,
                transform,
                ExifOrientationMode.RespectExifOrientation,
                ColorManagementMode.DoNotColorManage);
            pixelData.DetachPixelData().CopyTo(bitmap.PixelBuffer);
            return bitmap;
        }

        private async Task<IBuffer> ToBuffer(IRandomAccessStream stream)
        {
            var buffer = new Buffer((uint) stream.Size);
            var ibuffer = await stream.ReadAsync(buffer, (uint) stream.Size, InputStreamOptions.None);
            return ibuffer;
        }

        private async Task<BitmapSource> Resize(int width, int height, IRandomAccessStream source)
        {
            var small = new WriteableBitmap(width, height);
            var decoder = await BitmapDecoder.CreateAsync(source);
            var transform = new BitmapTransform();
            transform.ScaledHeight = (uint) height;
            transform.ScaledWidth = (uint) width;
            var pixelData =
                await
                    decoder.GetPixelDataAsync(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, transform,
                        ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage);
            pixelData.DetachPixelData().CopyTo(small.PixelBuffer);
            return small;
        }

        private async void settofavorate_Click(object sender, RoutedEventArgs e)
        {
            if (App.Loginuser == null)
            {
                await App.showmessage("请先登录");
                return;
            }
            var jsonstr = string.Empty;
            jsonstr = "{" + "\"" + "url" + "\"" + ":" + "\"" + homewebview.Source.AbsoluteUri + "\"" + "," + "\"" +
                      "name" + "\"" + ":" + "\"" + homewebview.DocumentTitle + "\"" + "," + "\"" + "userid" + "\"" + ":" +
                      "\"" + App.Loginuser.objectId + "\"" + "," + "\"" + "recordtype" + "\"" + ":" + "\"" +
                      HtmlUsedFunction.GetShareStringTyep(homewebview.Source.AbsoluteUri) + "\"" + "}";
            var content = new StringContent(jsonstr);
            var oneHttpResponseMessage =
                await
                    BmobWebsiteData.AddoneWebsiteBystringcontnet<HttpResponseMessage>(App.UserArticleorSiteUrl, content);
            if (oneHttpResponseMessage.StatusCode == HttpStatusCode.Created)
            {
                await App.showmessage("收藏成功");
            }
            else
            {
                await App.showmessage("收藏失败");
                //  MessageDialog one = new MessageDialog("收藏失败");
                //await  one.ShowAsync();
            }
        }

        private void share_Click(object sender, RoutedEventArgs e)
        {
            // Show the share UI
            DataTransferManager.ShowShareUI();
        }

        private void searchbtn_Click(object sender, RoutedEventArgs e)
        {
            //string text = searchbox.Text;
            //string url = "https://www.baidu.com/s?wd=" + text;
            //homewebview.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
        }

        private void openbtn_Click(object sender, RoutedEventArgs e)
        {
            //string str = searchbox.Text;
            //if (str.StartsWith("http") || str.StartsWith("www"))
            //{
            //    Uri oneuri = new Uri(str, UriKind.RelativeOrAbsolute);
            //    homewebview.Navigate(oneuri);
            //}
            //else if (false)
            //{

            //}
            //else
            //{ }
        }

        private async void homewebview_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
        {
            //secondpopup.IsOpen = true;
            //secondpopup.Width = 480;
            //secondpopup.Height = 750;
            //secondpopup.VerticalOffset = 100;
            //secondwebview.Navigate(args.Uri);
            //args.Handled = true;
            ////Button btn = new Button();
            ////wvpop.Child = btn;
            //secondwebview.LoadCompleted += Secondwebview_LoadCompleted;
            //return;
            //await  Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            // {
            //     Button btn = new Button();
            //     wvpop.Child = btn;
            // });

            //wvpop.IsOpen = true;
            ////secondpopup.HorizontalOffset =100;
            //secondwebview.Navigate(args.Uri);

            //return;
            //  App.titlebox.Text = App.currenturl.AbsoluteUri;
            if (App.Isdownloadstirngmode)
            {
                Debug.WriteLine("isdownloadstirngmode=FTRUE NEWWINDOWRE");
                var oldsrcreplacestr = "src=\"/";
                var newsrcreplacestr = "src=\"http://" + App.Currenturl.Host + "/";
                var oldhrefreplacestr = "href=\"/";
                var oldhrefwithemptyreplacestr = "href=\"/ ";
                var newhrefreplacestr = "href=\"http://" + App.Currenturl.Host + "/";
                App.Htmlstringcontent = await HtmlUsedFunction.gethtmlstring(App.Currenturl.AbsoluteUri);
                var ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
                var strr =
                    "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  window.external.notify(this.src);  }; } }";
                var IndexOfScriptTag = App.Htmlstringcontent.IndexOf("</head>");
                var InsertionScriptString = strr;
                //  int LengthOfScriptTag = ScrstriptTagString.Length;
                //  string InsertionScriptString = "function SayHelloWorld(wo) { window.external.notify(\"Hello World!\");}";
                var endscript = "</script>";
                // reuslt = reuslt.TrimEnd();
                App.Htmlstringcontent = App.Htmlstringcontent.Insert(IndexOfScriptTag,
                    ScriptTagString + InsertionScriptString + endscript);
                App.Htmlstringcontent =
                    App.Htmlstringcontent.Replace(oldsrcreplacestr, newsrcreplacestr)
                        .Replace(oldhrefreplacestr, newhrefreplacestr)
                        .Replace(oldhrefwithemptyreplacestr, newhrefreplacestr);
                Debug.WriteLine("new httpstring");
                Debug.WriteLine(App.Htmlstringcontent);
                if (App.Htmlstringcontent.Length > 500)
                {
                    if (App.Iswithoutpicmode)
                    {
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("jpg", "1jpg");
                        App.Htmlstringcontent = App.Htmlstringcontent.Replace("png", "1png");

                        Debug.WriteLine(App.Htmlstringcontent);
                        App.Picurllist = null;
                        App.Picurllist = await HtmlUsedFunction.getallimageByhtmlstring(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                    else
                    {
                        Debug.WriteLine(App.Htmlstringcontent);
                        homewebview.NavigateToString(App.Htmlstringcontent);
                    }
                }
                else
                {
                    if (App.Ismobile)
                    {
                        App.Navigatemobilemode(homewebview, App.Currenturl);
                    }
                    else
                    {
                        homewebview.Navigate(App.Currenturl);
                    }
                }
                //String STR = await HtmlUsedFunction.gethtmlstring(args.Uri.AbsoluteUri);

                //homewebview.NavigateToString(STR);
                //homewebview.Navigate(args.Uri);
                args.Handled = true;
            }
            else
            {
                Debug.WriteLine("isdownloadstirngmode=FALSE NEWWINDOWRE");
                App.Currenturl = args.Uri;
                if (App.Ismobile)
                {
                    App.Navigatemobilemode(homewebview, App.Currenturl);
                }
                else
                {
                    homewebview.Navigate(App.Currenturl);
                }
                args.Handled = true;
            }
        }

        private void Secondwebview_LoadCompleted(object sender, NavigationEventArgs e)
        {
            //   wvpop.Child = secondwebview;
        }

        private void backwebbtn_Click(object sender, RoutedEventArgs e)
        {
            if (homewebview.CanGoBack)
            {
                homewebview.GoBack();
                picstackpanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                if (Frame.CanGoBack)
                {
                    Frame.GoBack();
                }
            }
        }

        private async void webdefault_Click(object sender, RoutedEventArgs e)
        {
            var options = new LauncherOptions();
            options.TreatAsUntrusted = true;
            await Launcher.LaunchUriAsync(new Uri(homewebview.Source.AbsoluteUri), options);
            await Launcher.LaunchUriAsync(new Uri(homewebview.Source.AbsoluteUri, UriKind.RelativeOrAbsolute));
        }

        private async void SaveImage(IBuffer pixelBuffer)
        {
            //Rendu du composant Xaml, ici le graphique 'Syncfusion.Chart', sous forme d'image en mémoire.
            var renderTargetBitmap = new RenderTargetBitmap();
            //await renderTargetBitmap.RenderAsync(doughnutMadelin, (int)myDoughnutActualWidth, (int)myDoughnut.ActualHeight);
            // var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

            var localFolder = KnownFolders.PicturesLibrary;
            var filepicname = homewebview.DocumentTitle;
            //  var localFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            var saveFile = await localFolder.CreateFileAsync(filepicname + ".png", CreationCollisionOption.OpenIfExists);

            // Encodage de l'image en mémoire dans le fichier désigné sur le disque
            using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                encoder.SetPixelData(
                    BitmapPixelFormat.Rgba8,
                    BitmapAlphaMode.Ignore,
                    (uint) homewebview.ActualWidth,
                    (uint) homewebview.ActualHeight,
                    DisplayInformation.GetForCurrentView().RawDpiX,
                    DisplayInformation.GetForCurrentView().RawDpiY,
                    pixelBuffer.ToArray());

                await encoder.FlushAsync();
            }
            await App.showmessage("截图保存到了图片库");
            //MessageDialog one = new MessageDialog("截图保存到图片库");
            //await one.ShowAsync();
        }

        private void allpicbtn_Click(object sender, RoutedEventArgs e)
        {
            App.Currenturl = homewebview.Source;
            Frame.Navigate(typeof(PictureImagePage));
        }

        private void homewebview_ScriptNotify(object sender, NotifyEventArgs e)
        {
            var Text = e.Value;
            ParseUrl(Text);
        }

        private void confirmPurchase_Click(object sender, RoutedEventArgs e)
        {
            var f = channelbtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
        }

        private void flyout_Opened(object sender, object e)
        {
        }

        private void videobtnclick(object sender, RoutedEventArgs e)
        {
            var f = channelbtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();
            }
            var str = string.Empty;
            if (App.Ismobile)
            {
                if ((sender as Button).Content.ToString() == "视听")
                {
                    str = "http://hao567.github.io/v.html";
                }
                else if ((sender as Button).Content.ToString() == "学习")
                {
                    str = "http://hao567.github.io/learn.html";
                }
                else if ((sender as Button).Content.ToString() == "股票")
                {
                    str = "http://hao567.github.io/stock.html";
                }
                else if ((sender as Button).Content.ToString() == "聚分享")
                {
                    str = "http://hao567.github.io/share.html";
                }
                else if ((sender as Button).Content.ToString() == "生活")
                {
                    str = "http://hao567.github.io/life.html";
                }
                else if ((sender as Button).Content.ToString() == "游戏")
                {
                    str = "http://hao567.github.io/game.html";
                }
                else if ((sender as Button).Content.ToString() == "娱乐")
                {
                    str = "http://hao567.github.io/e.html";
                }
                else if ((sender as Button).Content.ToString() == "购物")
                {
                    str = "http://hao567.github.io/sale.html";
                }
                else if ((sender as Button).Content.ToString() == "程序员")
                {
                    str = "http://hao567.github.io/code.html";
                }
                else if ((sender as Button).Content.ToString() == "talk")
                {
                    str = "http://hao567.github.io/talk.html";
                }
                else if ((sender as Button).Content.ToString() == "其他")
                {
                    str = "http://hao567.github.io/t.html";
                }
                else if ((sender as Button).Content.ToString() == "应用中心")
                {
                    str = "http://datiancun.net/portal.php";
                }
                else if ((sender as Button).Content.ToString() == "uwp之家")
                {
                    str = "http://datiancun.net/portal.php";
                }
                else if ((sender as Button).Content.ToString() == "小游戏")
                {
                    str = "http://hao567.github.io/weigame.html";
                }
                else if ((sender as Button).Content.ToString() == "酷七市场")
                {
                    str = "http://app.ruanfenquan.com/";
                }
                else if ((sender as Button).Content.ToString() == "Foreign")
                {
                    str = "http://hao567.github.io/f.html";
                }
                else
                {
                    str = "http://www.hao123.com/video";
                }
            }
            else
            {
                if ((sender as Button).Content.ToString() == "视听")
                {
                    str = "http://www.hao123.com/video";
                }
                else if ((sender as Button).Content.ToString() == "小游戏")
                {
                    str = "http://hao567.github.io/weigame.html";
                }
                else if ((sender as Button).Content.ToString() == "Foreign")
                {
                    str = "http://hao567.github.io/f.html";
                }
                else if ((sender as Button).Content.ToString() == "学习")
                {
                    str = "http://www.copyedu.com/";
                }
                else if ((sender as Button).Content.ToString() == "娱乐")
                {
                    str = "http://hao567.github.io/e.html";
                }
                else if ((sender as Button).Content.ToString() == "购物")
                {
                    str = "http://hao567.github.io/sale.html";
                }
                else if ((sender as Button).Content.ToString() == "股票")
                {
                    str = "http://hao.360.cn/gupiaowz.html";
                }
                else if ((sender as Button).Content.ToString() == "聚分享")
                {
                    str = "http://hao567.github.io/share.html";
                }
                else if ((sender as Button).Content.ToString() == "talk")
                {
                    str = "http://hao567.github.io/talk.html";
                }
                else if ((sender as Button).Content.ToString() == "uwp之家")
                {
                    str = "http://datiancun.net/portal.php";
                }
                else if ((sender as Button).Content.ToString() == "酷七市场")
                {
                    str = "http://app.ruanfenquan.com/";
                }
                else if ((sender as Button).Content.ToString() == "其他")
                {
                    str = "http://hao567.github.io/t.html";
                }
                else if ((sender as Button).Content.ToString() == "生活")
                {
                    str = "http://hao.360.cn/shenghuowz.html";
                }
                else if ((sender as Button).Content.ToString() == "游戏")
                {
                    str = "http://game.2345.com/site.htm";
                }
                else if ((sender as Button).Content.ToString() == "程序员")
                {
                    str = "http://hao567.github.io/code.html";
                }
                else if ((sender as Button).Content.ToString() == "应用中心")
                {
                    str = "http://datiancun.net/portal.php";
                }
                else
                {
                    str = "http://www.hao123.com/video";
                }
            }
            App.Currenturl = new Uri(str, UriKind.RelativeOrAbsolute);
            if (App.Ismobile)
            {
                App.Navigatemobilemode(homewebview, App.Currenturl);
            }
            else
            {
                homewebview.Navigate(App.Currenturl);
            }
        }

        private void copyurlbtn_Click(object sender, RoutedEventArgs e)
        {
            if (homewebview.Source == null)
            {
                return;
            }
            var str = homewebview.DocumentTitle + "," + homewebview.Source.AbsoluteUri;
            var dp = new DataPackage();
            dp.SetText(str);
            Clipboard.SetContent(dp);
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            var rbtn = sender as RadioButton;
            var str = rbtn.Content.ToString();
            if (str == "水平")
            {
                // menurelativepanel.
            }
            else if (str == "垂直")
            {
            }
            else if (str == "上")
            {
            }
            else if (str == "下")
            {
            }
            else if (str == "左")
            {
            }
            else if (str == "右")
            {
            }
        }

        private void setrelativebtn_Click(object sender, RoutedEventArgs e)
        {
            menurelativepanel.Visibility = Visibility.Collapsed;
            picstackpanel.Visibility = Visibility.Collapsed;
            tbgridmenu.Visibility = Visibility.Visible;
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();
            }
        }

        private void rootlayout_DoubleTapped(object sender, DoubleTappedRoutedEventArgs e)
        {
            if (menurelativepanel.Visibility == Visibility.Visible)
            {
                menurelativepanel.Visibility = Visibility.Collapsed;
                picstackpanel.Visibility = Visibility.Collapsed;
                tbgridmenu.Visibility = Visibility.Visible;
            }
            else
            {
                menurelativepanel.Visibility = Visibility.Visible;
                tbgridmenu.Visibility = Visibility.Visible;
            }
        }

        private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
        {
            menurelativepanel.Visibility = Visibility.Visible;
            tbgridmenu.Visibility = Visibility.Collapsed;
        }

        private void channelbtn_Click(object sender, RoutedEventArgs e)
        {
        }

        private async void shareinappbtn_Click(object sender, RoutedEventArgs e)
        {
            var f = share.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();
            }
            var str = string.Empty;
            var userid = string.Empty;
            var username = string.Empty;
            if (App.Loginuser != null)
            {
                userid = App.Loginuser.objectId;
                username = App.Loginuser.username;
            }
            else
            {
                userid = "unknowuserid" + Guid.NewGuid();
                username = "匿名";
            }
            var jsonstr = string.Empty;
            jsonstr = "{" + "\"" + "url" + "\"" + ":" + "\"" + homewebview.Source.AbsoluteUri + "\"" + "," + "\"" +
                      "name" + "\"" + ":" + "\"" + homewebview.DocumentTitle + "\"" + "," + "\"" + "userid" + "\"" + ":" +
                      "\"" + userid + "\"" + "," + "\"" + "username" + "\"" + ":" + "\"" + username + "\"" + "," + "\"" +
                      "type" + "\"" + ":" + "\"" + HtmlUsedFunction.GetShareStringTyep(homewebview.Source.AbsoluteUri) +
                      "\"" + "," + "\"" + "keyword" + "\"" + ":" + "\"" + string.Empty + "\"" + "}";
            var content = new StringContent(jsonstr);
            var oneHttpResponseMessage =
                await BmobWebsiteData.AddOne<HttpResponseMessage>(App.ShareSiteorArticle, jsonstr);
            if (oneHttpResponseMessage.StatusCode == HttpStatusCode.Created)
            {
                await App.showmessage("分享成功");
                //MessageDialog one = new MessageDialog("分享成功");
                //await one.ShowAsync();
            }
            else
            {
                await App.showmessage("分享失败");
                //MessageDialog one = new MessageDialog("分享失败");
                //await one.ShowAsync();
            }
        }

        private void backgroundmodebtn_Click(object sender, RoutedEventArgs e)
        {
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
            var backgroudnwebview = new WebView(WebViewExecutionMode.SeparateThread);

            backgroudnwebview.Navigate(homewebview.Source);
            rootlayout.Children.Add(backgroudnwebview);
        }

        private void nightmodebtn_Click(object sender, RoutedEventArgs e)
        {
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
            //homewebview.DefaultBackgroundColor = Colors.Black;
            //   homewebview.Refresh();
            App.Isnightmode = true;
        }

        private void stopbtn_Click(object sender, RoutedEventArgs e)
        {
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
            homewebview.Stop();
        }

        private void refreshbtn_Click(object sender, RoutedEventArgs e)
        {
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
            homewebview.Refresh();
        }

        private void daymodebtn_Click(object sender, RoutedEventArgs e)
        {
            App.Isnightmode = false;
            var f = morebtn.Flyout as Flyout;
            if (f != null)
            {
                f.Hide();

                //rootPage.NotifyUser("You bought an item!", NotifyType.StatusMessage);
            }
            homewebview.DefaultBackgroundColor = Colors.White;
            //   homewebview.Refresh();
        }

        private async void addtodesktopbtn_Click(object sender, RoutedEventArgs e)
        {
            if (homewebview.Source == null)
            {
                return;
            }
            App.Addnamestr = homewebview.DocumentTitle;
            App.Addurlstr = homewebview.Source.AbsoluteUri;
            var one = new AddSitesContentDialog();

            await one.ShowAsync();

            //  App.addDesktopsites(App.addurlstr, App.homesiteurl);
        }

        private async void addtoofflinebtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //string str = string.Empty;
                //if (App.htmlstringcontent.Length > 200)
                //{
                //    str = App.htmlstringcontent;
                //}
                //else
                //{
                //    str = await HtmlUsedFunction.gethtmlstring(homewebview.Source.AbsoluteUri);
                //}

                //using (var db = new BloggingContext())
                //{
                //    var post = new Post { Posturl = homewebview.Source.AbsoluteUri, Content = str, Title = homewebview.DocumentTitle };

                //    db.Posts.Add(post);

                //    db.SaveChanges();
                //}
                await App.showmessage("添加成功");
                //MessageDialog one = new MessageDialog("添加成功");
                //await one.ShowAsync();
            }
            catch (Exception ex)
            {
            }
        }

        private void Add_Click()
        {
            _dragTranslation = new TranslateTransform();
            showmenubtn.RenderTransform = _dragTranslation;
        }

        private void Page_Holding(object sender, HoldingRoutedEventArgs e)
        {
        }

        private void mobilemodebtn_Click(object sender, RoutedEventArgs e)
        {
            App.Ismobile = true;
            var curr = Window.Current;
            var rootFrame = Window.Current.Content as Frame;
            rootFrame.Width = 466;
            rootFrame.Height = 800;
        }

        private async void showmenubtn_Click(object sender, RoutedEventArgs e)
        {
            // myevnet.btnevent -= showmenubtn_Click;
            var btn = sender as Button;
            if (btn.Content.ToString() == "菜单")
            {
                var pramslist = new List<string>();
                pramslist.Add("dfafdsa");
                try
                {
                    //string utyustr = await homewebview.InvokeScriptAsync("SayHelloWorld", pramslist);
                }
                catch (Exception ex)
                {
                }
                menurelativepanel.Visibility = Visibility.Visible;
                picstackpanel.Visibility = Visibility.Visible;
                return;
            }
            if (btn.Content.ToString() == "添加双屏")
            {
                var str = (sender as Button).Content.ToString();
                if (str == "添加双屏")
                {
                    var o = new RowDefinition();
                    var t = new RowDefinition();
                    //RowDefinitionCollection rows = new RowDefinitionCollection();
                    webviewgrid.RowDefinitions.Add(o);
                    webviewgrid.RowDefinitions.Add(t);
                    var secondview = new MyUserControl1(menurelativepanel);
                    webviewgrid.Children.Insert(1, secondview);
                    Grid.SetRow(secondview, 1);
                    _doublebtn = btn;
                    (sender as Button).Content = "移除双屏";
                    menurelativepanel.Visibility = Visibility.Collapsed;
                    picstackpanel.Visibility = Visibility.Collapsed;
                }
                else
                {
                    (sender as Button).Content = "添加双屏";
                    //  webviewgrid.RowDefinitions.RemoveAt(1);
                    webviewgrid.RowDefinitions.Clear();
                    webviewgrid.Children.RemoveAt(1);
                }
                return;
            }
            if (btn.Content.ToString() == "移除双屏")
            {
                var str = (sender as Button).Content.ToString();
                if (str == "添加双屏")
                {
                    var o = new RowDefinition();
                    var t = new RowDefinition();
                    //RowDefinitionCollection rows = new RowDefinitionCollection();
                    webviewgrid.RowDefinitions.Add(o);
                    webviewgrid.RowDefinitions.Add(t);
                    var secondview = new MyUserControl1(menurelativepanel);
                    webviewgrid.Children.Insert(1, secondview);
                    Grid.SetRow(secondview, 1);
                    (sender as Button).Content = "移除双屏";
                }
                else
                {
                    (sender as Button).Content = "添加双屏";
                    //  webviewgrid.RowDefinitions.RemoveAt(1);
                    webviewgrid.RowDefinitions.Clear();
                    webviewgrid.Children.RemoveAt(1);
                }
                return;
            }
            if (btn.Content.ToString() == "隐藏菜单")
            {
                menurelativepanel.Visibility = Visibility.Collapsed;
                picstackpanel.Visibility = Visibility.Collapsed;
                return;
            }
            if (btn.Content.ToString() == "复制网址")
            {
                if (homewebview.Source == null)
                {
                    return;
                }
                var str = App.Currenturl.AbsoluteUri;
                var dp = new DataPackage();
                dp.SetText(str);
                Clipboard.SetContent(dp);
                await App.showmessage("已经复制到剪贴板" + str);
                //  MessageDialog p = new MessageDialog("已经复制到剪贴板"+str);
                //await  p.ShowAsync();
            }
        }

        private void showmenubtn_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            //   WEBVI
            // Move the rectangle.
            _dragTranslation.X += e.Delta.Translation.X;
            _dragTranslation.Y += e.Delta.Translation.Y;
        }

        private async void savebtn(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).Tag == null)
            {
                return;
            }
            var str = (sender as Button).Tag.ToString();
            picstackpanel.Visibility = Visibility.Collapsed;


            //BitmapImage bmpfd = new BitmapImage(new Uri(str, UriKind.RelativeOrAbsolute));
            var myClient = new HttpClient();
            var memorystream = await myClient.GetStreamAsync(new Uri(str, UriKind.Absolute));

            var memStream = new MemoryStream();
            await memorystream.CopyToAsync(memStream);
            memStream.Position = 0;
            var bitmap = new BitmapImage();

            var pne = new Random();
            var jk = pne.Next(1, 100000000);
            var wbmp = new WriteableBitmap(300, 300);
            await wbmp.SetSourceAsync(memStream.AsRandomAccessStream());
            if (str.EndsWith("png"))
            {
                await HtmlUsedFunction.SaveToPngImage(wbmp, PickerLocationId.PicturesLibrary, "多彩浏览器器" + jk);
            }
            else
            {
                await HtmlUsedFunction.SaveTojpegImage(wbmp, PickerLocationId.PicturesLibrary, "多彩浏览器器" + jk);
            }
            memorystream.Dispose();
            (sender as Button).Tag = null;
            (sender as Button).Foreground = new SolidColorBrush(Colors.Black);
        }

        private async void video_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var btn = sender as Button;
                if (btn.Tag == null)
                {
                    await App.showmessage("没获取到地址,请先点击");
                    //MessageDialog one = new MessageDialog("没获取到地址,请先点击");
                    //await one.ShowAsync();
                    return;
                }
                var source = new Uri(btn.Tag.ToString());
                var randow = new Random();

                var destination = randow.Next(1, 100000) + "duocai.mp4";

                var destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync(
                    destination, CreationCollisionOption.GenerateUniqueName);

                var downloader = new BackgroundDownloader();
                var download = downloader.CreateDownload(source, destinationFile);
                await download.StartAsync();
                (sender as Button).Tag = null;
                (sender as Button).Foreground = new SolidColorBrush(Colors.Black);
                menurelativepanel.Visibility = Visibility.Collapsed;
                // picstackpanel.Visibility = Visibility.Collapsed;
                // Attach progress and completion handlers.
                //HandleDownloadAsync(download, true);
            }
            catch (Exception ex)
            {
                //  LogException("Download Error", ex);
            }
        }

        private async void picsavetolibrarybtnclick(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            //   var stringstr = "var a= document.activeElement; ";
            //   var stringstr2 = "return a;";
            //var testhtml= await   homewebview.InvokeScriptAsync("eval", new[] { stringstr ,stringstr2})
            if (btn.Tag == null)
            {
                var statusbar = StatusBar.GetForCurrentView();
                statusbar.ProgressIndicator.Text = "没获取到地址,请先点击";
                await statusbar.ProgressIndicator.ShowAsync();
                //MessageDialog one = new MessageDialog("没获取到地址,请先点击");
                //await one.ShowAsync();
                return;
            }
            var source = new Uri(btn.Tag.ToString());
            var randow = new Random();
            picstackpanel.Visibility = Visibility.Collapsed;
            var destination = randow.Next(1, 100000) + "duocai.jpg";

            var destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                destination, CreationCollisionOption.GenerateUniqueName);

            var downloader = new BackgroundDownloader();
            var download = downloader.CreateDownload(source, destinationFile);
            await download.StartAsync();
        }

        private async void savehtml_Click(object sender, RoutedEventArgs e)
        {
            var lastindexl = homewebview.Source.AbsoluteUri.LastIndexOf('/');
            var name = homewebview.Source.AbsoluteUri.Substring(lastindexl,
                homewebview.Source.AbsoluteUri.Length - lastindexl);
            Debug.WriteLine(name + "doanloadnma");
            //    Button btn = sender as Button;
            ////   var stringstr = "var a= document.activeElement; ";
            ////   var stringstr2 = "return a;";
            ////var testhtml= await   homewebview.InvokeScriptAsync("eval", new[] { stringstr ,stringstr2})
            //if (btn.Tag == null)
            //{
            //    MessageDialog one = new MessageDialog("没获取到地址,请先点击");
            //    await one.ShowAsync();
            //    return;
            //}
            //  Uri source = new Uri(btn.Tag.ToString());
            var randow = new Random();
            var destination = string.Empty;
            if (name.Contains(".jpg") || name.Contains(".gif") || name.Contains(".jpeg") || name.Contains(".png"))
            {
                if (name.Contains(".gif"))
                {
                    destination = homewebview.DocumentTitle + ".gif";
                }
                else if (name.Contains(".png"))
                {
                    destination = homewebview.DocumentTitle + ".png";
                }
                else
                {
                    destination = homewebview.DocumentTitle + ".jpg";
                }
            }
            else
            {
                destination = homewebview.DocumentTitle + ".html";
            }

            var destinationFile = await KnownFolders.PicturesLibrary.CreateFileAsync(
                destination, CreationCollisionOption.GenerateUniqueName);

            var downloader = new BackgroundDownloader();
            var download = downloader.CreateDownload(homewebview.Source, destinationFile);
            await download.StartAsync();
            savehtml.Content = "保存到了图片文件夹";
            savehtml.FontSize = 8;
        }

        private void avoidscreenbtnclick(object sender, RoutedEventArgs e)
        {
            //timer.Interval = TimeSpan.FromMilliseconds(1000);
            // timer.Tick += Timer_Tick;
            //timer.Start();
        }

        private void Timer_Tick(object sender, object e)
        {
            i = i + 1;
            Debug.WriteLine(i);
            // avoidscreenbtn.Content = i.ToString();
            //UrlMkGetSessionOption
            //string[] stringstr ={"2+2"};
            //string[] arguments = { "document.title" };
            //string[] activetag = { "document.activeElement.tagName" };
            //string[] activetscript = { "document.scripts" };
            //string[] cookietscript = { "document.cookie" };
            //string[] allimagetscript = { "document.images" };
            //string result =await homewebview.InvokeScriptAsync("eval", arguments);
            //string testhtml = await homewebview.InvokeScriptAsync("eval", stringstr);
            //string activetagtesthtml = await homewebview.InvokeScriptAsync("eval", activetag);
            //string activetscriptres = await homewebview.InvokeScriptAsync("eval", activetscript);
            //string cookietscriptres = await homewebview.InvokeScriptAsync("eval", cookietscript);
            //string allimagetscriptstr = await homewebview.InvokeScriptAsync("eval", allimagetscript);
            //Debug.WriteLine(result);
            //Debug.WriteLine(testhtml);
            //Debug.WriteLine(activetagtesthtml);
            //Debug.WriteLine(activetscriptres);
            // Debug.WriteLine(cookietscriptres);
            //Debug.WriteLine(allimagetscriptstr);
        }

        private void goall_Click(object sender, RoutedEventArgs e)
        {
            homewebview.Stop();
            if (!homewebview.CanGoBack)
            {
                Frame.GoBack();
            }
            while (homewebview.CanGoBack)
            {
                homewebview.GoBack();
            }
        }

        private void Clickl_Click(object sender, RoutedEventArgs e)
        {
            var str = (sender as Button).Content.ToString();
            if (str == "添加浏览器")
            {
                var o = new RowDefinition();
                var t = new RowDefinition();
                //RowDefinitionCollection rows = new RowDefinitionCollection();
                webviewgrid.RowDefinitions.Add(o);
                webviewgrid.RowDefinitions.Add(t);
                var secondview = new MyUserControl1(menurelativepanel);
                webviewgrid.Children.Insert(1, secondview);
                Grid.SetRow(secondview, 1);
                (sender as Button).Content = "移除浏览器";
            }
            else
            {
                (sender as Button).Content = "添加浏览器";
                //  webviewgrid.RowDefinitions.RemoveAt(1);
                webviewgrid.RowDefinitions.Clear();
                webviewgrid.Children.RemoveAt(1);
            }
        }

        private void webviewgrid_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
        {
            App.Issecondwebviewmanipulated = false;
        }

        private void avoidscreenbtn_Click(object sender, RoutedEventArgs e)
        {
            if (_dispRequest == null)
            {
                // Activate a display-required request. If successful, the screen is 
                // guaranteed not to turn off automatically due to user inactivity.
                _dispRequest = new DisplayRequest();
                _dispRequest.RequestActive();
            }
        }

        private async void sharepicbtn_Click(object sender, RoutedEventArgs e)
        {
            var btn = sender as Button;
            var api = "https://api.bmob.cn/1/classes/sharepictable";
            var userdic = new Dictionary<string, string>();
            userdic.Add("picurl", btn.Tag.ToString());
            picstackpanel.Visibility = Visibility.Collapsed;
            (sender as Button).Tag = null;
            (sender as Button).Foreground = new SolidColorBrush(Colors.Black);

            userdic.Add("weburl", App.Currenturl.AbsoluteUri);

            userdic.Add("pictitle", homewebview.DocumentTitle);

            userdic.Add("pictags", homewebview.DocumentTitle);
            var userid = string.Empty;
            var username = string.Empty;
            if (App.Loginuser != null)
            {
                userid = App.Loginuser.objectId;
                username = App.Loginuser.username;
            }
            else
            {
                userid = "unknowuserid" + Guid.NewGuid();
                username = "unkownusename" + "匿名用户";
            }
            //    userdic.Add("userid", userid);
            userdic.Add("shareusername", username);
            //userdic.Add("mainwebspace", mainwebspacebox.Text);
            //userdic.Add("likesbox", likesbox.Text);
            //userdic.Add("introducebox", introducebox.Text);

            var jsonstrdic = RequestHelper.DictionaryTojsonstr(userdic);
            var responce = await BmobWebsiteData.AddoneWebsite<object>(api, jsonstrdic);
            if (responce.StatusCode == HttpStatusCode.Created)
            {
                await App.showmessage("分享成功");
                //  MessageDialog one = new MessageDialog("注册成功,请登录");
                //await  one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
            else
            {
                await App.showmessage("分享失败");
                // MessageDialog one = new MessageDialog("注册失败");
                //await one.ShowAsync();
                // registerbrn.IsEnabled = true;
            }
        }


        private async void Clipboard_ContentChanged(object sender, object e)
        {
            //WebViewBrush b = new WebViewBrush();
            //b.Opacity = 0.2;
            //b.SetSource(homewebview);
            //b.Redraw();
            //GoBaidu.Fill = b;

            var dpv = Clipboard.GetContent();
            var url = "https://www.baidu.com/s?wd=" + await dpv.GetTextAsync();
            homewebview.Navigate(new Uri(url));


            var b = new WebViewBrush();
            b.SetSource(homewebview);
            b.Redraw();
            GoBaidu.Fill = b;
            homewebview.Visibility = Visibility.Collapsed;
        }


        private async void GoBaidu_RightTapped(object sender, RightTappedRoutedEventArgs e)
        {
            GoBaidu.Visibility = Visibility.Collapsed;
            GoBaidu.Fill = new SolidColorBrush(Colors.Transparent);
            var p = new Popup();
            p.Child = new Button
            {
                Content = "用百度搜索"
            };
            p.IsOpen = true;
            p.HorizontalOffset = e.GetPosition(webviewgrid).X;
            p.VerticalOffset = e.GetPosition(webviewgrid).Y;
            //  Debug.WriteLine(e.GetPosition(webviewgrid).X + "x" + e.GetPosition(webviewgrid).Y + "y");

            //FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);

            p = new Popup();

            var txt = await Clipboard.GetContent().GetTextAsync();
            if (Regex.IsMatch(txt, @"[a-z]+"))
            {
                p.Child = new Button
                {
                    Content = "翻译成中文"
                };
            }
            else
            {
                p.Child = new Button
                {
                    Content = "用百度搜索"
                };
            }

            p.Child.Tapped += BaiduFlyout_Click;
            p.IsOpen = true;
            p.HorizontalOffset = e.GetPosition(webviewgrid).X;
            p.VerticalOffset = e.GetPosition(webviewgrid).Y;
        }

        private async void BaiduFlyout_Click(object sender, RoutedEventArgs e)
        {
            var popupText = (sender as Button).Content.ToString();
            switch (popupText)
            {
                case "翻译成中文":
                    await new MessageDialog("搜索的还没写").ShowAsync();
                    break;
                case "用百度搜索":
                    var dpv = Clipboard.GetContent();
                    var url = "https://www.baidu.com/s?wd=" + await dpv.GetTextAsync();
                    homewebview.Navigate(new Uri(url));
                    break;
                default:
                    break;
            }

            homewebview.Visibility = Visibility.Visible;
            GoBaidu.Fill = null;
            if (_popup != null)
            {
                _popup.IsOpen = false;
            }
        }

        private void GoBaidu_Holding(object sender, HoldingRoutedEventArgs e)
        {
            Debug.WriteLine(e.GetPosition(webviewgrid).X + "x" + e.GetPosition(webviewgrid).Y + "y");
        }

        private async void sharescreen_Click(object sender, RoutedEventArgs e)
        {
            var stream = new InMemoryRandomAccessStream();

            await homewebview.CapturePreviewToStreamAsync(stream);
            var stream1 = stream.AsStream();
            await HtmlUsedFunction.upload(stream1, "test.jpeg", homewebview.DocumentTitle);
        }
    }
}